from io import BytesIO

from PIL import Image

from django.core.files.uploadedfile import InMemoryUploadedFile


def cut_image(image, iw, x, y, x2, y2):
    """
    剪裁图片, 并返回为 InMemoryUploadedFile 实例
    """
    img = Image.open(image)
    i_x, i_y = img.size
    # 重置图片尺寸
    x_s = iw
    y_s = round(i_y * x_s / i_x)
    out = img.resize((x_s, y_s), Image.ANTIALIAS)  # resize image with high-quality

    # 剪裁图片
    left = x
    upper = y
    right = x2
    lower = y2
    region = out.crop((left, upper, right, lower))  # left, upper, right, lower

    # 返回为 InMemoryUploadedFile 实例
    region_io = BytesIO()
    region.save(region_io, format=image.content_type.split('/')[-1].upper())
    img = InMemoryUploadedFile(region_io, image.field_name, image.name, image.content_type, image.size,
                               image.charset, image.content_type_extra)
    return img
